package com.ytkj.digitalConstruction.controller.user;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.util.StringUtils;
import com.ytkj.digitalConstruction.ReturnCode;
import com.ytkj.digitalConstruction.entity.user.User;
import com.ytkj.digitalConstruction.httpbean.user.ReqUser;
import com.ytkj.digitalConstruction.httpbean.user.UserLogin;
import com.ytkj.digitalConstruction.httpbean.user.req.ReqChanPass;
import com.ytkj.digitalConstruction.httpbean.user.resbean.UserDeptId;
import com.ytkj.digitalConstruction.service.role.RoleService;
import com.ytkj.digitalConstruction.service.user.UserService;
import com.ytkj.digitalConstruction.util.WebTokenUtil;


/**
 * 用户请求入口
 * 
 * @author Pete
 * @author momei
 * @Date 2017年12月7日
 */
@RestController
@RequestMapping("users")
public class UserController {
	private final static Logger log = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

	/**
	 * 用户登录
	 * 
	 * @param userLogin
	 * @return
	 */
	@PostMapping("/login")
	public ReturnCode login(@RequestBody @Valid UserLogin userLogin, BindingResult bindingResult) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		
		log.info("开始登陆");
		String webToken = userService.login(userLogin.getUserName(), userLogin.getPasswd());
		if(webToken == null) {
			return new ReturnCode.Builder().Success(false).Msg("用户名或密码错误！").build();
		}
		log.info("获取webToken成功");
		//获取token中的userId
		Integer userId = (Integer)WebTokenUtil.parseWebToken(webToken,"userId");
		Set<Integer> permissionList = roleService.getPermissionListByUserId(userId);
		if(permissionList.isEmpty()) {
			return new ReturnCode.Builder().Success(true).Msg("权限不足请向管理员获取权限!").Object(0).build();
		}
		return new ReturnCode.Builder().Success(true).Msg("登陆成功").Object(webToken).build();
	}

	/**
	 * 添加用户
	 * 
	 * @return
	 * @throws Exception 
	 */
	@PostMapping("/add")
	public ReturnCode add(@RequestBody @Valid ReqUser req, BindingResult bindingResult) throws Exception {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		//判断密码长度
//		if(StringUtils.isEmpty(req.getPasswd()) == false) {
//			int len = req.getPasswd().length();
//			if((len > 5 && len < 16) == false) {
//				log.error("密码长度不合法！");
//				return new ReturnCode.Builder().Success(false).Msg("密码长度必须在5到15之间").build();
//			}
//		}
		
		//判断手机号码是否已存在
		if(userService.isExistedMobile(req.getMobile())){
			log.error("UserController add Exception:mobile existed!");
			return new ReturnCode.Builder().Success(false).Msg("手机号码已注册！").build();
		}
		//判断登录名是否已存在
		if(userService.isExistedUserName(req.getUserName())){
			log.error("UserController add Exception:userName existed!");
			return new ReturnCode.Builder().Success(false).Msg("用户名已注册！").build();
		}
		//校验实体部门是否唯一
		if(!userService.checkDept(req.getDeptIds())) {
			log.error("UserController add Exception:userName existed!");
			return new ReturnCode.Builder().Success(false).Msg("参数有误！").build();
		}
		String resMsg = userService.addUser(req);
		if (!StringUtils.isEmpty(resMsg)) {
			log.error("添加用户失败");
			return new ReturnCode.Builder().Success(false).Msg(resMsg).build();
		}
		log.info("添加用户开始");
		return new ReturnCode.Builder().Success(true).Msg("添加用户成功").Object(req).build();
	}

	/**
	 * 删除用户
	 * 
	 * @param userId
	 * @return
	 */
	
	@GetMapping("/delete/{id}")
	public ReturnCode delete(@PathVariable("id") Integer userId) {
		// 判断参数是否为空
		if (userId == null || userId == 0) {
			log.error("传入参数不为空");
			return new ReturnCode.Builder().Success(false).Msg("传入参数不为空").build();
		}
		//判断是否有未完成的施工计划
		if(userService.isHaveUnfinishProcess(userId)) {
			log.error("传入参数不为空");
			return new ReturnCode.Builder().Success(false).Msg("该用户有未完成的流程，不允许删除！").build();
		}
		// 删除用户
		
		boolean result = userService.deleteUser(userId);
		if (result == false) {
			log.error("删除用户失败");
			return new ReturnCode.Builder().Success(false).Msg("删除用户失败").build();
		}
		return new ReturnCode.Builder().Success(true).Msg("删除用户成功！").Object(userId).build();
	}

	/**
	 * 修改用户信息
	 * 
	 * @return
	 * @throws Exception 
	 */
	@PostMapping("/update")
	public ReturnCode update(@RequestBody @Valid ReqUser req, BindingResult bindingResult){
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		// 更新用户信息
		String dingMsg = userService.updateUser(req);
		if (!StringUtils.isEmpty(dingMsg)) {
			return new ReturnCode.Builder().Success(false).Msg(dingMsg).build();
		}
		return new ReturnCode.Builder().Success(true).Msg("修改用户成功").build();
	}

	/**
	 * 获取用户所在部门
	 * 
	 * @return
	 */
	@GetMapping("/depts")
	public ReturnCode getDepts(HttpServletRequest request) {

		String webToken = request.getHeader("x-access-token");
		User currentUser = userService.getUserByWebToken(webToken);
		if(currentUser == null){			
			return new ReturnCode.Builder().Success(false).Msg("获取当心用户信息失败!").build();
		}
		//获取当前用户所在部门
		List<Map<String, Object>> userDepts = userService.getDepts(currentUser.getUserId());
		log.info("获取用户所在部门开始");
		//return new ReturnCode.Builder().Success(true).Msg("获取用户所在部门开始").Object(deptService.deptTree(null, userDepts)).build();
		return new ReturnCode.Builder().Success(true).Msg("获取用户所在部门开始").Object(userDepts).build();
	}
	
	/**
	 * 获取用户所在实体部门树
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/depts/real")
	public ReturnCode findRealDept(HttpServletRequest request) {
		String webToken = request.getHeader("x-access-token");
		User currentUser = userService.getUserByWebToken(webToken);
		if(currentUser == null){			
			return new ReturnCode.Builder().Success(false).Msg("获取当心用户信息失败!").build();
		}
		//获取用户所在部门
		List<Map<String,Object>> userRealDepts = userService.findRealDepts(currentUser.getUserId());
		log.info("获取用户所在部门开始");
		//return new ReturnCode.Builder().Success(true).Msg("获取用户所在部门开始！").Object(deptService.deptTree(null, userRealDepts)).build();
		return new ReturnCode.Builder().Success(true).Msg("获取用户所在部门开始！").Object(userRealDepts).build();
	}
	

	/**
	 * 根据WebToken获取用户信息
	 * 
	 * @return
	 */
	@GetMapping("/getUserByWebToken")
	public ReturnCode getUserByWebToken(HttpServletRequest request) {
		String webToken = request.getHeader("x-access-token");
		User user = userService.getUserByWebToken(webToken);
		if(user == null) {
			log.error("根据WebToken获取用户信息失败");
			return new ReturnCode.Builder().Success(false).Msg("根据WebToken获取用户信息失败").Object(user).build();
		}
		return new ReturnCode.Builder().Success(true).Msg("根据WebToken获取用户信息成功").Object(user).build();
	}

	/**
	 * 手机端登录
	 * 
	 * @param userId
	 * @return webtoken
	 */
	@GetMapping("/mobile/webToken/{userId}")
	public ReturnCode webToken(@PathVariable("userId") Integer userId){
		if(userId == null || userId < 0){
			log.error("UserController loginByMobile Exception: 传入参数有误！");
			return new ReturnCode.Builder().Success(false).Msg("传入参数有误！").Object(userId).build();
		}
		
		String webToken = userService.webToken(userId);
		
		if(StringUtils.isEmpty(webToken)){
			log.error("UserController loginByMobile Exception: 获取webToken失败！");
			return new ReturnCode.Builder().Success(false).Msg("获取webToken失败！").Object(userId).build();
		}
		return new ReturnCode.Builder().Success(true).Msg("获取webToken成功！").Object(webToken).build();
	}
	
	/**
	 * 退出登录
	 * 
	 * @param request
	 * @param request
	 * @return
	 */
	@GetMapping("/logout")
	public ReturnCode logout(HttpServletRequest request) {

		String webToken = request.getHeader("x-access-token");
		boolean success = userService.logout(webToken);
		if(success == false) {
			log.error("UserController logout Exception: 注销失败！");
			return new ReturnCode.Builder().Success(false).Msg("注销失败！").build();
		}
		return new ReturnCode.Builder().Success(true).Msg("注销成功").build();
	}
	
	/**
	 * 获取用户虚拟部门实体部门
	 * @param userId
	 * @return
	 */
	@GetMapping("/dept/{userId}")
	public ReturnCode findDept(@PathVariable("userId") Integer userId){
		if(userId < 0) {
			log.error("UserController findDept Exception: 参数有误！");
			return new ReturnCode.Builder().Success(false).Msg("参数有误！").build();
		}
		UserDeptId depts = userService.findDept(userId);
		return new ReturnCode.Builder().Success(true).Msg("查询成功！").Object(depts).build();
	}
	
	/**
	 * 修改密码
	 * 
	 * @param req
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	@PostMapping("/password/new")
	public ReturnCode changPassword(@RequestBody @Valid ReqChanPass req, BindingResult bindingResult,HttpServletRequest request) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		//校验新旧密码是否相同
		if(req.getOldPassword().equals(req.getNewPassword())) {
			return new ReturnCode.Builder().Success(false).Msg("新旧密码不能相同！").build();
		}
		//判断旧密码是否正确
		String webToken = request.getHeader("x-access-token");
		User user = userService.getUserByWebToken(webToken);
		if(user == null) {
			return new ReturnCode.Builder().Success(false).Msg("获取当前用户失败！").build();
		}
		if(!userService.checkOldPassword(user.getUserName(),req.getOldPassword())) {
			return new ReturnCode.Builder().Success(false).Msg("旧密码错误！").build();
		}
		
		//修改密码
		if(!userService.changePassword(user.getUserId(),req.getNewPassword())) {
			return new ReturnCode.Builder().Success(false).Msg("修改密码失败！").build();
		}
		return new ReturnCode.Builder().Success(true).Msg("修改密码成功！").build();
	}

	@PostMapping("/upload")
	public ReturnCode upload(@PathVariable("file ") MultipartFile file){
		log.info("Import success");

		String fileName[] = file.getOriginalFilename().split("\\.");
		String name = fileName[1];
		if(name.indexOf("xls") == -1){
			log.error("文件格式不正确");
			return new ReturnCode.Builder().Success(false).Msg("文件格式不正确！").build();
		}

		try {
			InputStream input = file.getInputStream();  //建立输入流
			Workbook wb = new XSSFWorkbook(input);

			userService.readExcelToDb(wb, 0, 2, 0);
			return new ReturnCode.Builder().Success(true).Msg("上传成功！").build();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("上传失败！ ");
			return new ReturnCode.Builder().Success(false).Msg("上传失败！").build();
		}
	}

}
